package com.jackrain.nea.web.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.core.query.ColumnLink;
import com.jackrain.nea.core.schema.*;
import com.jackrain.nea.core.webaction.WebAction;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.PairTable;
import com.jackrain.nea.util.Tools;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.util.WebUtils;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.query.QueryListConfig;
import com.jackrain.nea.web.query.QueryListConfigManager;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.query.QueryUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

@Slf4j
@RestController
@Api(value = "TableQueryController", description = "获取查询字段rest")
public class TableQueryController {



    @Autowired
    private  TableManager tm;

    @Autowired
    private PropertiesConf pconf;


    @RequestMapping(path = "/p/cs/getTableQuery",method = {RequestMethod.GET,RequestMethod.POST})
    public JSONObject getTableQuery(HttpServletRequest request,
                                   @RequestParam(value="tableid", required=false)Integer TableId,
                                    @RequestParam(value="getcmd", required=false,defaultValue="n") String getcmd,
                                    @RequestParam(value="table", required=false) String tabname) throws Exception {
        JSONArray retValue = new JSONArray();

        ValueHolder valueHolder = new ValueHolder();


        try {
            UserImpl userWeb = (UserImpl) request.getSession().getAttribute("user");
            QuerySession qsession = QueryUtils.createQuerySession(userWeb);
            TableManager tm = qsession.getTableManager();
            
            
            Table table = null;
    
            if(TableId!=null) {
                table = tm.getTable(TableId);
            } else {
                table = tm.getTable(tabname);
            }

            if(table==null) {
                throw  new NDSException("tablenull");
            }

            QueryListConfig qlc = QueryListConfigManager.getInstance().getDefaultQueryListConfig(table.getId(), tm, userWeb.getSecurityGrade());

            List<ColumnLink> qColumns = qlc.getConditions();
            for (int i = 0; i < qColumns.size(); i++) {
                ColumnLink clink = qColumns.get(i);
                Column column = clink.getLastColumn();
                String desc = clink.getDescription(userWeb.getLocale());
                String inputName = clink.toHTMLString();
                int inputSize = (column.getReferenceTable() != null ? column.getReferenceTable().getAlternateKey().getLength() : column.getLength());
                DisplaySetting ds = column.getDisplaySetting();
                PairTable values = column.getValues(userWeb.getLocale());
                JSONObject querydao = new JSONObject();
                querydao.put("colid", column.getId());
                querydao.put("colinputName", inputName);
                querydao.put("coldesc", desc);
                String defval = QueryUtils.replaceVariables(column.getDefaultValue(), qsession);


                JSONObject jor = column.getJSONProps();


                if (ds.getObjectType() == DisplaySetting.OBJ_TEXT) {
                    if (column.getType() == Column.DATE) {
                        querydao.put("display", "OBJ_DATE");
                        if (jor != null && jor.containsKey("daterange")) {
                            querydao.put("daterange", jor.getIntValue("daterange"));
                        } else {
                            querydao.put("daterange", pconf.getProperty("r3.daterange", 7));
                        }

                    } else if (column.getType() == Column.DATENUMBER) {
                        querydao.put("display", "OBJ_DATENUMBER");
                        if (jor != null && jor.containsKey("daterange")) {
                            querydao.put("daterange", jor.getIntValue("daterange"));
                        } else {
                            querydao.put("daterange", pconf.getProperty("r3.daterange", 7));
                        }

                    } else if (column.getReferenceTable() != null) {
                        querydao.put("display", "OBJ_FK");
                       // boolean ISdropdown=Tools.getBoolean(column.getReferenceTable().isDropdown(),false);
                        querydao.put("fkobj", new FKObjectQueryModel( false, column.getReferenceTable(), column).FKObjectToJsonObj());
                    }
                }

                if (ds.getObjectType() == DisplaySetting.OBJ_CHECK) {
                    querydao.put("display", "OBJ_CHECK");
                    if (values != null) {
                        JSONArray combobox = new JSONArray();
                        Iterator i1 = values.keys();
                        Iterator i2 = values.values();
                        while (i1.hasNext() && i2.hasNext()) {
                            JSONObject groupval = new JSONObject();
                            String limitdesc = String.valueOf(i2.next());
                            String limitval = String.valueOf(i1.next());
                            // add = so will match identically
                            //o.put(tmp1,"="+tmp2); // tmp1 is limit-description, tmp2 is limit-value
                            groupval.put("limitdesc", limitdesc);
                            groupval.put("limitval", limitval);
                            groupval.put("limitdis",  Tools.getBoolean(limitval, false));
                            combobox.add(groupval);
                        }
                        querydao.put("combobox", combobox);
                    }

                    if("isactive".equalsIgnoreCase(column.getName())){
                        querydao.put("default", "Y");
                    }
                    //querydao.put("default", Tools.getBoolean(defval, false));
                }

                if (ds.getObjectType() == DisplaySetting.OBJ_SELECT) {
                    querydao.put("display", "OBJ_SELECT");
                    if (values != null) {
                        JSONArray combobox = new JSONArray();
                        Iterator i1 = values.keys();
                        Iterator i2 = values.values();
                        while (i1.hasNext() && i2.hasNext()) {
                            JSONObject groupval = new JSONObject();
                            String limitdesc = String.valueOf(i2.next());
                            String limitval = String.valueOf(i1.next());
                            // add = so will match identically
                            //o.put(tmp1,"="+tmp2); // tmp1 is limit-description, tmp2 is limit-value
                            groupval.put("limitdesc", limitdesc);
                            groupval.put("limitval", limitval);
                            combobox.add(groupval);
                        }
                        querydao.put("combobox", combobox);
                    }

                    if("isactive".equalsIgnoreCase(column.getName())){
                        querydao.put("default", "Y");
                    }

                    if("status".equalsIgnoreCase(column.getName())){
                        querydao.put("default", 1);
                    }

                }

                if (ds.getObjectType() == DisplaySetting.OBJ_RAIDO) {
                    querydao.put("display", "OBJ_RADIO");
                    if (values != null) {
                        JSONArray combobox = new JSONArray();
                        Iterator i1 = values.keys();
                        Iterator i2 = values.values();
                        while (i1.hasNext() && i2.hasNext()) {
                            JSONObject groupval = new JSONObject();
                            String limitdesc = String.valueOf(i2.next());
                            String limitval = String.valueOf(i1.next());
                            // add = so will match identically
                            //o.put(tmp1,"="+tmp2); // tmp1 is limit-description, tmp2 is limit-value
                            groupval.put("limitdesc", limitdesc);
                            groupval.put("limitval", limitval);
                            combobox.add(groupval);
                        }
                        querydao.put("combobox", combobox);
                    }
        
                }

//                if (!querydao.containsKey("default"))
//                    querydao.put("default", defval);

                retValue.add(querydao);

            }

            if (Tools.getBoolean(getcmd, false)) {

                /**------check permission---**/
                int perm = userWeb.getPermission(table.getSecurityDirectory(tm));
                //SecurityWebUtils.getPermission(table.getSecurityDirectory(tm), userWeb.id);

                //  String search_show=userWeb.getUserOption("SEARCH_SHOW","N");

                boolean isWriteEnabled = (((perm & 3) == 3));
                boolean isSubmitEnabled = (((perm & 5) == 5));
                boolean canVoid = table.isActionEnabled(Table.VOID) && isWriteEnabled;
                boolean canExport = (((perm & 17) == 17));
                boolean canDelete = table.isActionEnabled(Table.DELETE) && isWriteEnabled;
                boolean canAdd = table.isActionEnabled(Table.ADD) && isWriteEnabled;
                boolean canModify = table.isActionEnabled(Table.MODIFY) && isWriteEnabled;
                boolean canSubmit = table.isActionEnabled(Table.SUBMIT) && isSubmitEnabled;
                boolean isUnSubmitEnabled = (((perm & 9) == 9));
                boolean canUNsubmit=table.isActionEnabled(Table.UNSUBMIT)&&isUnSubmitEnabled;


                //boolean hasCommand=  canDelete || canSubmit || canVoid;

                //SecurityWebUtils.checkDirectoryReadPermission(table.getSecurityDirectory(tm), userWeb);

                //boolean isStatusValid= table.isActionEnabled(Table.SUBMIT);

                JSONObject tableObj = new JSONObject(true);
                tableObj.put("id", table.getId());
                tableObj.put("desc", table.getDescription(userWeb.getLocale()));
                tableObj.put("actionADD", canAdd);
                //tableObj.put("actionMODIFY", canModify);
                tableObj.put("actionDELETE", canDelete);
                tableObj.put("actionSUBMIT", canSubmit);
                tableObj.put("actionUNSUBMIT", canUNsubmit);
                tableObj.put("actionGROUPSUBMIT", canSubmit && table.isActionEnabled(Table.GROUPSUBMIT));
                tableObj.put("actionVOID", canVoid);
                tableObj.put("actionIMPORT", canAdd);
                tableObj.put("actionEXPORT", canExport);
                
                

                valueHolder.put("tabcmd", tableObj);


                JSONArray waListButtons = new JSONArray();
                JSONArray waListMenuItems = new JSONArray();

                HashMap actionEnv = new HashMap();
                actionEnv.put("maintable", table.getId());
                actionEnv.put("querySession", qsession);

                List<WebAction> was = table.getWebActions(WebAction.DisplayTypeEnum.ListButton);
                for (int wasi = 0; wasi < was.size(); wasi++) {
                    WebAction wa = was.get(wasi);
                    if (wa.canDisplay(actionEnv)) {
                        waListButtons.add(wa.toObj(userWeb.getLocale(), actionEnv));
                    }
                }

                if (waListButtons.size() > 0) {
                    valueHolder.put("waListButtons", waListButtons);
                }

                was = table.getWebActions(WebAction.DisplayTypeEnum.ListMenuItem);
                for (int wasi = 0; wasi < was.size(); wasi++) {
                    WebAction wa = was.get(wasi);
                    if (wa.canDisplay(actionEnv)) {
                        waListMenuItems.add(wa.toObj(qsession.getLocale(), actionEnv));
                    }
                }

                if (waListMenuItems.size() > 0) {
                    valueHolder.put("waListMenuItems", waListMenuItems);
                }

            }

            JSONObject data= new JSONObject();
            data.put("dataarry",retValue);
            data.put("tableid",table.getId());
            data.put("table",table.getName());
            data.put("searchFoldnum",table.getSearchFoldnum());
            data.put("isIsshowextendpage",table.getIsshowextendpage());
            
            String hidecolumns=WebUtils.getHideColumn(userWeb.getId(),table.getId());
            data.put("hidecolumns",hidecolumns);
            
            boolean isfavorite=WebUtils.isFavorite(userWeb.getId(),"table",table.getId());
            data.put("isfavorite",isfavorite);
            
            valueHolder.put("code", 0);
            valueHolder.put("datas", data);


            return valueHolder.toJSONObject();
        }catch (Exception e){
            e.printStackTrace();
            valueHolder.put("code", -1);
            valueHolder.put("msg", e.getMessage());
            return valueHolder.toJSONObject();
        }
    }

}
